<template>
  <div class="be-loading-container" :class="[{ 'is-open': showLoading, 'is-fullscreen': fullscreen }, className]">
    <span class="be-loading-dot">
      <i v-for="index in 4" :key="index" class="be-loading-dot-i"></i>
    </span>
    <div v-if="text" class="be-loading-text">{{ text }}</div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'

// 定义 Props 接口
interface Props {
  text?: string // 文字
  loading?: boolean // loading 状态开启
  className?: string // 类名
  fullscreen?: boolean // 是否全屏
}

// 定义组件选项
defineOptions({ name: 'BeLoading' })

// props
const props = withDefaults(defineProps<Props>(), {
  text: '',
  loading: false,
  className: '',
  fullscreen: false
})

// state
const showLoading = ref(false)

// 监视 props.loading 的变化
watch(
  () => props.loading,
  (show) => {
    showLoading.value = show // 隐藏加载动画
  },
  {
    immediate: true // 初始立即调用
  }
)
</script>
<style lang="scss" scoped>
/* 定义旋转动画 */
@keyframes rotate-ani {
  to {
    transform: rotate(405deg);
  }
}

/* 定义加载点动画 */
@keyframes spin-move-ani {
  to {
    opacity: 1; /* 逐渐显示 */
  }
}
.be-loading-container {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 100;
  display: flex;
  visibility: hidden;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  opacity: 0;
  transition: all 500ms;
  &.is-open {
    visibility: visible;
    opacity: 1;
  }
  &.is-fullscreen {
    position: fixed;
    z-index: 9999;
  }
  .be-loading-text {
    margin-top: 16px;
    font-size: 12px;
    line-height: 16px;
  }
  .be-loading-dot {
    position: relative;
    width: 36px;
    height: 36px;
    font-size: 30px;
    transform: rotate(45deg);
    animation: rotate-ani 1.2s infinite linear;
  }
  .be-loading-dot i {
    position: absolute;
    width: 16px;
    height: 16px;
    background-color: var(--primary);
    border-radius: 50%;
    opacity: 0.3;
    transform: scale(0.75);
    transform-origin: 50% 50%;
    animation: spin-move-ani 1s infinite linear alternate;
  }
  .be-loading-dot i:nth-child(1) {
    top: 0;
    left: 0;
  }
  .be-loading-dot i:nth-child(2) {
    top: 0;
    right: 0;
    animation-delay: 0.4s;
  }
  .be-loading-dot i:nth-child(3) {
    right: 0;
    bottom: 0;
    animation-delay: 0.8s;
  }
  .be-loading-dot i:nth-child(4) {
    bottom: 0;
    left: 0;
    animation-delay: 1.2s;
  }
}
</style>
